package com.hedl.practice.diyJava.multithreading.thread_synchronization.example;

public class Study_2 {
    //synchronized的错误使用

    public static void main(String[] args) throws InterruptedException {
        var add = new AddThread_1();
        var dec = new DecThread_1();
        add.start();
        dec.start();
        add.join();
        dec.join();
        System.out.println(Counter_1.count);
    }
}
class Counter_1 {
    //这里写了两类，来做锁；导致了锁不同步问题；一般一把锁可以进行两个数据之间的操作
    public static final Object lock1 = new Object();
    public static final Object lock2 = new Object();
    public static int count = 0;
}

class AddThread_1 extends Thread {
    public void run() {
        for (int i=0; i<10000; i++) {
            synchronized(Counter_1.lock1) {
                Counter_1.count += 1;
            }
        }
    }
}

class DecThread_1 extends Thread {
    public void run() {
        for (int i=0; i<10000; i++) {
            synchronized(Counter_1.lock2) {
                Counter_1.count -= 1;
            }
        }
    }
}
